﻿//Date extension
Date.prototype.formate = function (formate) {
    var date = this;
    formate = formate || "yyyy-MM-dd";

    formate = formate.replace('dd', (date.getDate() < 10 ? '0' : '') + date.getDate());
    formate = formate.replace('MM', (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1));
    formate = formate.replace('yyyy', (date.getFullYear()));
    formate = formate.replace('hh', (date.getHours() < 10 ? '0' : '') + date.getHours());
    formate = formate.replace('mm', (date.getMinutes() < 10 ? '0' : '') + date.getMinutes());
    formate = formate.replace('ss', (date.getSeconds() < 10 ? '0' : '') + date.getSeconds());
    return formate;
};

//String extension
//将/Date(...)类型的字符串转化成符合format的日期
String.prototype.DateStringConvert = function (format) {
    var dateString = this;
    if (/\/Date\(-([0-9]+(.*?))\)\//.test(dateString)) {
        return '';
    }
    if (/\/Date\(([0-9]+(.*?))\)\//.test(dateString)) {
        return dateString.replace(/\/Date\(([0-9]+(.*?))\)\//, function (str, m1) {
            var d = new Date(parseInt(m1, 10));
            return d.formate(format);
        });
    }
    return dateString;
}

//将字符串转换成时间 2012-12-12
String.prototype.toDate = function () {
    var dateString = this;
    var dateSplit = dateString.split("-"),
        _sDate = dateSplit[0] + '/' + dateSplit[1] + '/' + dateSplit[2];

    return new Date(_sDate);
};

//将json数据里面所有的数字转换成字符串
var ConvertNumberToStringInJson = function (jsonData) {
    for (var j in jsonData) {
        if (jsonData[j] && !isNaN(jsonData[j])) {
            jsonData[j] = jsonData[j].toString();
        }
    }
    return jsonData;
};

var checkSpecialKeys = function (e) {
    if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 35 && e.keyCode != 36 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40)
        return false;
    else
        return true;
};

var checkTextAreaMaxLength = function (textBox, e, length) {

    var mLen = textBox["MaxLength"];
    if (null == mLen)
        mLen = length;

    var maxLength = parseInt(mLen);
    if (!checkSpecialKeys(e)) {
        if (textBox.value.length > maxLength - 1) {
            if (window.event)//IE
            {
                e.returnValue = false;
                return false;
            }
            else//Firefox
                e.preventDefault();
        }
    }
};

var openDialog = function (url, width, height) {
    var _w = 1160, _h = 630;
    _w = width || _w;
    _h = height || _h;

    var iTop = 20; //获得窗口的垂直位置;
    var iLeft = (window.screen.availWidth - 10 - _w) / 2; //获得窗口的水平位置;
    window.open(url, "_blank", "width=" + _w + ",height=" + _h + ",top=" + iTop + ",left=" + iLeft + ",resizable=1,scrollbars=1,fullscreen=0");
}

var showModuleDialog = function (url, width, height) {
    var _w = 1160, _h = 650;
    _w = width || _w;
    _h = height || _h;
    openDialog(url, _w, _h);
}

var closeWindow = function () {
    window.close();
}

var GetParentWindow = function () {
    var opener = window.opener;
    if (!opener) {
        //for IE window.opener=undefined
        opener = window.dialogArguments;
    }
    if (!opener) {
        opener = window.parent;
    }

    return opener;
}

//必填项验证
var clientValidate = function (button, containerID) {
    var container = $(button).parents('body');
    if (containerID) {
        container = $('#' + containerID);
    }

    var errors = [];
    container.find('[data-required-info]').each(function () {
        var input = $(this);

        var val = "HasValue", error = $(this).attr('data-required-info'), type = $(this).attr('type');

        //日期控件
        if (input.hasClass('easyui-datebox')) input = input.next('.datebox').find('input[type="text"]');

        //radio button
        if (type == "radio" || type == "checkbox") {
            var groupName = input.attr('name');
            input = container.find('[name="' + groupName + '"]');
            if (input.is(':visible')) {
                input = input.filter(':checked');
                if (input.length == 0) {
                    errors.push(error);
                }
            }
        } else {

            if (input.length && input.is(':visible')) {
                val = $.trim(input.val());
            }

            if (val == "") {
                errors.push(error);
            }
        }
    });

    return errors;
};

//日期比较
//return date1 - date2 >0 (includeEquals == true => return date1 - date2 >= 0)
var dateCompare = function (containerID, date1, date2, includeEquals) {
    var container = $('#' + containerID);

    if (container.length && container.is(':visible')) {

        if (date1 && date2) {
            if (includeEquals) {
                return date2 >= date1;
            }
            return date2 > date1;
        }
    }

    return true;
};

//两日期之间相差天数 date2-date1
var datediff = function (date1, date2) {
    if (date1 && date2) {
        var _date1 = date1.toDate(),
            _date2 = date2.toDate();

        if (_date1 && _date2) {
            return (_date2.getTime() - _date1.getTime()) / (24 * 3600 * 1000);
        }
    }
}

//打开责任人搜索页面
//数据来自PlanGroupUser
var openResponsibleSearch = function () {
    showModuleDialog('/PlanManagement/SearchResponsibleByGroup', 700, 560);
};

//用户搜索
//isFocusOwnLocation --- 是否限定查找本单位人员
//isNotSingleSelect ----是否限制单选
var openSearchUser = function (isFocusOwnLocation, isNotSingleSelect) {
    isFocusOwnLocation = isFocusOwnLocation || false;
    isNotSingleSelect = isNotSingleSelect || false;
    showModuleDialog('/PlanManagement/SearchResponsible?IsOwner=' + isFocusOwnLocation + '&isNotSingle=' + isNotSingleSelect, 700, 560);
}



//添加责任人
var addResponsible = function (data) {
    data = data[0];
    var usernameInput = $('[data-from="username"]'),
        userIDInput = $('[data-from="userid"]');
    if (usernameInput.length && userIDInput.length) {
        usernameInput.val(data["DisplayName"]);
        userIDInput.val(data["ID"]);
    }
};

//巡检对象
var InspObj = {};

InspObj.doSearch = function (url) {
    showModuleDialog(url, 700, 500);
};

//业务系统搜索
InspObj.doBusinessSearch = function (value) {
    InspObj.doSearch('/PlanManagement/SearchBussiness?Key=' + value);
};

InspObj.doServerSearch = function (value) {
    InspObj.doSearch('/PlanManagement/SearchServer?Key=' + value);
};

InspObj.doNetSearch = function (value) {
    InspObj.doSearch('/PlanManagement/SearchNet?Key=' + value);
};

InspObj.doSafetySearch = function (value) {
    InspObj.doSearch('/PlanManagement/SearchSafety?Key=' + value);
};

InspObj.doDBSearch = function (value) {
    InspObj.doSearch('/PlanManagement/SearchDB?Key=' + value);
};

InspObj.doMiddlewareSearch = function (value) {
    InspObj.doSearch('/PlanManagement/SearchMiddleware?Key=' + value);
};

InspObj.doStorageSearch = function (value) {
    InspObj.doSearch('/PlanManagement/SearchStorage?Key=' + value);
};

InspObj.doBackupSearch = function (value) {
    InspObj.doSearch('/PlanManagement/SearchBackUp?Key=' + value);
};

//获取要添加的数据模型
InspObj.getData = function (container) {
    var data = {}, flag = true;

    container.find('[data-source]').each(function () {

        if ($(this).hasClass('easyui-combobox') && $(this).combobox('getValue')) {
            data[$(this).attr('data-source')] = $(this).combobox('getValue');
        } else if ($(this).val()) {

            data[$(this).attr('data-source')] = $(this).val();
        }

        flag &= $.trim($(this).val()) != "";
    });

    if (!flag) {
        $.messager.alert('提醒', '请填写所有输入项！');
        return {};
    }

    return data;
};

//添加数据之后清空输入框
InspObj.clearInput = function (container) {
    container.find('[data-source]').each(function () {
        $(this).val('');
    });
};

//向对应的Datagrid中添加单行数据
//data[Array]要添加的数据数组
InspObj.AddSystem = function (containerID, tableID, data) {

    var addRow = function (input) {
        if (!$.isEmptyObject(input)) {
            input['Ope'] = '<a class="deleteRow">删除</a>';
            $('#' + tableID).datagrid('appendRow', input);
            InspObj.clearInput($("#" + containerID));
        }
    };

    if (data && data.length) {
        $.each(data, function (index, obj) {
            addRow(obj);
        });
    } else {
        addRow(this.getData($("#" + containerID)));
    }
};

//注册Datagrid
InspObj.RegisterGrid = function (tableID) {
    $('#' + tableID).datagrid({
        onClickCell: function (rowIndex, field, value) {
            if (field == "Ope" && value) {
                $('#' + tableID).datagrid('deleteRow', rowIndex);
            }
        }
    });
};

/*
 * 获取添加过的巡检项的Request_ID列表
 */
InspObj.GetRequestIDList = function (tableID) {
    var list = [];
    if ($('#' + tableID).length) {
        var rows = $('#' + tableID).datagrid('getData').rows;
        if (rows && rows.length) {
            for (var i = 0; i < rows.length; i++) {
                if (rows[i]["Request_ID"]) {
                    list.push(rows[i]["Request_ID"]);
                }
            }
        }
    }

    return list;
};

/*
 * 记住datagrid之前页面的所有选择
 */
InspObj.SelectArray = {};
InspObj.OnSelect = function (index, row, tableID) {
    var data = InspObj.SelectArray[tableID];
    if (!data) InspObj.SelectArray[tableID] = [];

    for (var i = 0; i < InspObj.SelectArray[tableID].length; i++) {
        if (InspObj.SelectArray[tableID][i]["Request_ID"] == row["Request_ID"]) { return; }
    }

    InspObj.SelectArray[tableID].push(row);
};

InspObj.OnUnSelect = function (index, row, tableID) {
    var data = InspObj.SelectArray[tableID];
    if (!data) InspObj.SelectArray[tableID] = [];

    for (var i = 0; i < InspObj.SelectArray[tableID].length; i++) {
        if (InspObj.SelectArray[tableID][i]["Request_ID"] == row["Request_ID"]) {
            InspObj.SelectArray[tableID].splice(i, 1);
            return;
        }
    }
};

InspObj.OnSelectAll = function (rows, tableID) {
    var data = InspObj.SelectArray[tableID];
    if (!data) InspObj.SelectArray[tableID] = [];

    for (var i = 0; i < rows.length; i++) {
        var row = rows[i], forSwitch = true;

        for (var j = 0; j < InspObj.SelectArray[tableID].length && forSwitch; j++) {
            if (InspObj.SelectArray[tableID][j]["Request_ID"] == row["Request_ID"]) { forSwitch = false; }
        }

        if (forSwitch)
            InspObj.SelectArray[tableID].push(row);
    }
};

InspObj.OnUnSelectAll = function (rows, tableID) {
    var data = InspObj.SelectArray[tableID];
    if (!data) InspObj.SelectArray[tableID] = [];

    for (var i = 0; i < rows.length; i++) {
        var row = rows[i], forSwitch = true;

        for (var j = 0; j < InspObj.SelectArray[tableID].length && forSwitch; j++) {
            if (InspObj.SelectArray[tableID][j]["Request_ID"] == row["Request_ID"]) {
                InspObj.SelectArray[tableID].splice(j, 1);
                forSwitch = false;
            }
        }

    }
};

InspObj.onLoadSuccess = function (rows, tableID, dg) {
    var data = InspObj.SelectArray[tableID];
    if (!data) InspObj.SelectArray[tableID] = [];

    for (var i = 0; i < rows.length; i++) {
        var index = i;
        var row = rows[i];
        (function () {
            for (var i = 0; i < InspObj.SelectArray[tableID].length; i++) {
                if (InspObj.SelectArray[tableID][i]["Request_ID"] == row["Request_ID"]) {
                    dg.datagrid('checkRow', index);
                    return;
                }
            }
        })();
    }
};

InspObj.AddBusinessSys = function (data) {
    this.AddSystem("businessAddContainer", "BusinessSystems", data);
};

InspObj.AddServerSys = function (data) {
    this.AddSystem("serverAddContainer", "ServerSystem", data);
};

InspObj.AddNetSys = function (data) {
    this.AddSystem("netAddContainer", "NetSystem", data);
};

InspObj.AddSafetyEqui = function (data) {
    this.AddSystem("safetyAddContainer", "SafetyEquipment", data);
};

InspObj.AddDBSystem = function (data) {
    this.AddSystem("dbAddContainer", "DatabaseSys", data);
};

InspObj.AddMiddlewareSystem = function (data) {
    this.AddSystem("middlewareAddContainer", "MiddlewareSys", data);
};

InspObj.AddStorageSystem = function (data) {
    this.AddSystem("storageAddContainer", "StorageSys", data);
};

InspObj.AddBackupSystem = function (data) {
    this.AddSystem("backupAddContainer", "BackupSys", data);
};

//获取所有填写的巡检对象
InspObj.GetAllObj = function () {
    var data = {};

    $('[data-field]').each(function () {
        var id = $(this).attr('id'),
            propName = $(this).attr('data-field');

        if (propName) {
            if ($(this)[0].tagName.toUpperCase() == "TABLE") {
                data[propName] = $('#' + id).datagrid('getData').rows;
                $.each(data[propName], function (i, row) {
                    delete row["Ope"];
                });

            }
            else {
                data[propName] = {};
                $(this).find('[data-column]').each(function (i, value) {
                    var type = $(this).attr('type'),
                        columnName = $(this).attr('data-column');

                    if (type == "checkbox") {
                        data[propName][columnName] = $(this).is(':checked');
                    }
                });
            }

        }
    });



    return data;
};

//保存计划之前的验证
var planValidate = function (button) {

    //已存在的计划单，只验证非空项
    if ($('#detailID').val()) {

        var errors = clientValidate(button);

        if (errors.length > 0) {
            var content = '<ul class="warnTip">';

            $.each(errors, function (index, _e) {
                content += "<li>" + _e + "</li>"
            });

            content += "</ul>";
            $.messager.alert('提醒', content, 'warning');
        } else {
            SavePlan();
        }
        return true;
    }

    var errors = clientValidate(button);

    var dates = [
        { containerID: 'detail_1', startDate: 'startDate_Once', endDate: 'endDate_Once' },
        { containerID: 'detail_2', startDate: 'startDate_Day', endDate: 'endDate_Day' },
        { containerID: 'detail_3', startDate: 'startDate_Week', endDate: 'endDate_Week' },
        { containerID: 'detail_4', startDate: 'startDate_Month', endDate: 'endDate_Month' }
    ];
    var today = new Date().formate();

    var selectedCycle = $('input[name="cycle"]:checked').val() * 1 - 1;
    if (selectedCycle >= 0) {
        var val = dates[selectedCycle];
        var date1 = $('#' + val["startDate"]).datebox('getValue'),
            date2 = $('#' + val["endDate"]).datebox('getValue');
        if (!dateCompare(val["containerID"], date1, date2)) {
            errors.push("结束时间必须大于开始时间!");
        }

        if (!dateCompare(val["containerID"], today, date1, true)) {
            errors.push("开始时间必须大于等于今天!");
        }
    }

    if ($('#chooseDays').is(':visible') && $('#chooseDays').is(':checked')) {
        var range = $('#numberRange'),
            min = range.attr('min') * 1,
            max = range.attr('max') * 1,
            val = range.val() * 1;

        if (isNaN(val)) {
            errors.push("单次任务持续天数格式不正确 !");
        } else {
            if (val > max || val < min) {
                errors.push("单次任务持续天数在" + min + "-" + max + "天之间 !");
            }
        }

    }

    //电子公告验证
    if ($('#electronicBulletin').is(':checked')) {
        if (!(
               $('#bulletinTitle').val()
            && $('#bulletinContent').val()
            && $('#bulletinStartDate').datebox('getValue')
            && $('#bulletinEndDate').datebox('getValue'))) {
            errors.push('请填写完整电子公告！');
        } else {
            var today = new Date().formate(),
                date1 = $('#bulletinStartDate').datebox('getValue'),
                date2 = $('#bulletinEndDate').datebox('getValue');

            if (!dateCompare("bulletinDetail", date1, date2)) {
                errors.push("电子公告失效时间必须大于开始时间!");
            }

            //if (!dateCompare("bulletinDetail", today, date1, true)) {
            //    errors.push("电子公告开始时间必须大于等于今天!");
            //}
        }

    }

    if (errors.length > 0) {
        var content = '<ul class="warnTip">';

        $.each(errors, function (index, _e) {
            content += "<li>" + _e + "</li>"
        });

        content += "</ul>";
        $.messager.alert('提醒', content, 'warning');
    } else {
        SavePlan();
    }
};

//周期数据保存
var cycleSave = function () {
    var cycleList = [], cycle = {};
    cycle["PlanType"] = $('[name="cycle"]:checked').val();
    cycle["IsLengthValid"] = 1;
    switch (cycle["PlanType"]) {
        case "1": //一次
            cycle["BeginDate"] = $('#startDate_Once').datebox("getValue") == "" ? null : $('#startDate_Once').datebox("getValue");
            cycle["EndDate"] = $('#endDate_Once').datebox("getValue") == "" ? null : $('#endDate_Once').datebox("getValue");
            cycle["Length"] = datediff(cycle["BeginDate"], cycle["EndDate"]) + 1;
            cycleList.push(cycle);
            break;
        case "2": //每天
            cycle["BeginDate"] = $('#startDate_Day').datebox("getValue") == "" ? null : $('#startDate_Day').datebox("getValue");
            cycle["EndDate"] = $('#endDate_Day').datebox("getValue") == "" ? null : $('#endDate_Day').datebox("getValue");
            cycle["Length"] = 1;
            cycle["HolidayInValid"] = $('#excludeWeekend').is(':checked') ? 1 : 0;
            cycleList.push(cycle);
            break;
        case "3": //每周
            cycle["BeginDate"] = $('#startDate_Week').datebox("getValue") == "" ? null : $('#startDate_Week').datebox("getValue");
            cycle["EndDate"] = $('#endDate_Week').datebox("getValue") == "" ? null : $('#endDate_Week').datebox("getValue");
            cycle["Length"] = 7;
            cycle["Day"] = $('[name="week"]:checked').val();
            cycleList.push(cycle);
            break;
        case "4": //每月
            $('#monthSelectList').find('input[type="checkbox"]:checked').each(function () {
                var month = $(this).val(), day = $('[name="dayList"]:checked').val() * 1;
                var item = {};
                item["PlanType"] = 4;
                item["BeginDate"] = $('#startDate_Month').datebox("getValue") == "" ? null : $('#startDate_Month').datebox("getValue");
                item["EndDate"] = $('#endDate_Month').datebox("getValue") == "" ? null : $('#endDate_Month').datebox("getValue");
                var chooseDay = $('#chooseDays').is(':checked');
                item["IsLengthValid"] = chooseDay ? 1 : 0;
                item["Length"] = 31;
                if (chooseDay) {
                    item["Length"] = $('#numberRange').val();
                }

                item["Month"] = month;
                item["Day"] = day;
                item["IsLastDay"] = $('#day_last').is(':checked') ? 1 : 0;
                cycleList.push(item);
            });
            break;
    }

    $.each(cycleList, function (i, val) {
        ConvertNumberToStringInJson(val);
    });

    return cycleList;
};


//组合计划模型，保存计划
var planSave = function (data) {

    data["ID"] = $('#detailID').val();
    //基本输入数据
    $('[data-model-source]').each(function (i, input) {
        var propName = $(this).attr('data-model-source'),
            tagName = $(this).get(0).tagName.toUpperCase(),
            type = $(this).attr('type');

        if (propName) {
            if (type == "text" || type == "hidden" || tagName == "SELECT" || tagName == "TEXTAREA") {
                data[propName] = $(this).val().toString();
            }
        }
    });

    //是否启用
    data["Invalid"] = $('#start').is(':checked') ? 1 : 0;

    var cycle = ConvertNumberToStringInJson(cycleSave());
    data = ConvertNumberToStringInJson(data);

    //不启用时，给予提醒
    if (data["Invalid"] == 0) {
        $.messager.confirm('提醒', '确认暂时不启用该计划吗?', function (r) {
            if (r) {
                postSave({ job: data, cycle: cycle, bulletin: data["bulletin"] ? data["bulletin"] : null });
            }
        });
    } else {
        $.messager.confirm('提醒', '确认保存该计划吗?', function (r) {
            if (r) {
                postSave({ job: data, cycle: cycle, bulletin: data["bulletin"] ? data["bulletin"] : null });
            }
        });
    }
};
var postSave = function (data) {
    $.ajax({
        type: 'POST',
        url: '/PlanManagement/Create',
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function (res) {
            if (res == "OK") {
                $.messager.alert('确认', '保存成功！', '', function () {
                    closeWindow();
                });
            }
            if (res == "Error") {
                $.messager.alert('错误', '保存失败!', 'error');
            }

            if (res == "计划名已存在") {
                $.messager.alert('错误', '计划名已存在!', 'error');
            }
        }
    });
};

var taskSave = function (data, files) {

    //task基本数据保存
    $('[data-model-source]').each(function (i, input) {
        var propName = $(this).attr('data-model-source'),
            tagName = $(this).get(0).tagName.toUpperCase(),
            type = $(this).attr('type');

        if (propName) {
            if (type == "text" || type == "hidden" || tagName == "SELECT" || tagName == "TEXTAREA") {
                data[propName] = $(this).val().toString();
            }
        }
    });

    $.messager.confirm('提醒', '确认提交该任务吗?', function (r) {
        if (r) {
            postSaveTask(data, files);
        }
    });

};
var postSaveTask = function (data, files) {
    $.ajax({
        type: 'POST',
        url: '/PlanManagement/SaveTask',
        contentType: 'application/json',
        data: JSON.stringify({ task: data, files: files }),
        success: function (res) {
            if (res == "OK") {
                $.messager.alert('确认', '保存成功！', '', function () {
                    closeWindow();
                });
            }
            if (res == "Error") {
                $.messager.alert('错误', '保存失败!', 'error');
            }
        }
    });
};

//获取待办个数在日历中显示
var getTaskPendingCalendar = function (year, month) {
    $.post('/PlanManagement/GetCalendarPending', { Year: year, month: month }, function (res) {
        if (res) {
            for (var item in res) {
                var day = item.split('/').join(',');
                var td = $('td[abbr="' + day + '"]');
                if (res[item] && res[item].length) {

                    var pending = res[item];
                    var content = '<ul>';
                    $.each(pending, function (index, item) {
                        if (item["OverFlag"] == 1) {
                            content += '<li><a href="#">' + item["TaskName"] + '<span style="color:red;">(已过期)</span></a></li>';
                        } else {
                            content += '<li><a href="#">' + item["TaskName"] + '</a></li>';
                        }
                    });
                    content += '</ul>';
                    td.addClass('canlendar-pending');
                    td.find('div').append('<span class="pending-tip">' + res[item].length + '</span>');
                    td.tooltip({
                        position: 'top',
                        content: content
                    });
                }
            }
        }
    });
};

$(function () {
    $.messager.defaults.ok = "确定";
    $.messager.defaults.cancel = "取消";

    $('.calendar-prevmonth,.calendar-nextmonth,.calendar-prevyear,.calendar-nextyear,.calendar-menu-month').die('click').live('click', function () {
        var calendar = $('#taskCalendar').calendar('options');
        getTaskPendingCalendar(calendar["year"], calendar["month"]);
    });
});